package com.usian.admin.service.impl

import com.alibaba.fastjson.JSONArray
import com.usian.admin.feign.ArticleFeign
import com.usian.admin.feign.WemediaFeign
import com.usian.admin.mapper.AdChannelMapper
import com.usian.admin.mapper.AdSensitiveMapper
import com.usian.admin.service.WemediaNewsAutoScanService
import com.usian.common.aliyun.GreeTextScan
import com.usian.common.aliyun.GreenImageScan
import com.usian.common.fastdfs.FastDFSClient
import com.usian.model.admin.dtos.NewsAuthDto
import com.usian.model.article.pojos.ApArticle
import com.usian.model.article.pojos.ApArticleConfig
import com.usian.model.article.pojos.ApArticleContent
import com.usian.model.common.dtos.PageResponseResult
import com.usian.model.common.dtos.ResponseResult
import com.usian.model.common.enums.AppHttpCodeEnum
import com.usian.model.media.pojos.WmNews
import com.usian.model.media.vo.WmNewsVo
import com.usian.utils.common.SensitiveWordUtil
import io.seata.spring.annotation.GlobalTransactional
import org.apache.catalina.Host
import org.codehaus.jettison.json.JSONObject
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import java.util.*


typealias mm=MutableMap<String,Any>
@Service
open class WemediaNewsAutoScanServiceImpl : WemediaNewsAutoScanService {
    @Autowired
    lateinit var articleFeign: ArticleFeign
    @Autowired
    lateinit var wemediaFeign: WemediaFeign
    //部署
    @Autowired
    lateinit var fastDFSClient: FastDFSClient
    @Autowired
    lateinit var adChannelMapper: AdChannelMapper
    //阿里云自动审核图片
    @Autowired
    lateinit var greenImageScan: GreenImageScan
    //阿里云文本审核
    @Autowired
    lateinit var greenTextScan: GreeTextScan

    //敏感词库
    @Autowired
   lateinit var adSensitiveMapper: AdSensitiveMapper

    @Value("\${fdfs.url}")
    lateinit var basePath :String

    @GlobalTransactional
    override fun autoScanByMediaNewsId(id: Int) {
        if(id==null){
            println("审核id为空")
            return
        }

        var wmNews = wemediaFeign.findById(id)
        if (wmNews==null){
            println("文章不存在$id")
            return
        }

        /**
         * 人工审核通过之后状态为4，直接保存数据和创建索引
         */
        if (wmNews.status.toInt()==4){
            saveAppArticle(wmNews);
            return;
        }

        /**
         * 待发布
         * 文章状态为8且时间到了之后 （发布时间<=当前时间） 直接保存数据
         */
        if (wmNews.status.toInt()==8 &&wmNews.publishTime.time <= System.currentTimeMillis()){
            saveAppArticle(wmNews);
            return;
        }

        /**
         * 审核文章状态为待审核的文章（第一次审核）
         */
        if(wmNews.status.toInt()==1){
            var contentAndImageResult :mm =handleTextAndImages(wmNews)
            handleTextScan(contentAndImageResult["content"].toString(),wmNews)
            handleImagesScan(contentAndImageResult["images"] as MutableList<String>,wmNews)
            handleSensitive(contentAndImageResult["content"].toString(),wmNews)
            if (wmNews.publishTime.time>System.currentTimeMillis()){
                updateWmNews(wmNews,8,"审核通过，待发布")
            }
            saveAppArticle(wmNews)
        }
    }

    /**
     * 文本敏感词审核
     */
    private fun handleSensitive(toString: String, wmNews: WmNews) {
        val sensitive = adSensitiveMapper.findAllSensitive()
        SensitiveWordUtil.initMap(sensitive)
        val matchWords = SensitiveWordUtil.matchWords(toString)
        if (matchWords.isNotEmpty()){
            println("敏感词过滤没有通过，包含了敏感词:$matchWords")
            updateWmNews(wmNews,2,"文章中包含了敏感词")
            return
        }

    }


    /**
     * 阿里云三方图片审核
     */
    private fun handleImagesScan(any: MutableList<String>, wmNews: WmNews?) {
        if(any !=null && any.size!=0){
            val list:MutableList<ByteArray> = mutableListOf()
            any.forEach {
                //将图片路径的前面部分替换成”“
                var newPath= it.replace(basePath,"")
                //以第一个 / 分割
                var index= newPath.indexOf("/")
                //获取索引位置
                var groupName=newPath.substring(0,index)
                //每次索引+1（包左不包右）
                var pathName=newPath.substring(index+1)
                //根据前索引和最后的索引找到图片路径下载（下载实在后台做的，下载的是 byte【】）
                var download=fastDFSClient.download(groupName,pathName)
                //将下载的图片添加到集合中（不可能只有一张图片）
                list.add(download)
            }
            greenImageScan.imageScan(list)
        }
    }

    /**
     * 阿里云三方文本自动审核（有无敏感词）
     */
    private fun handleTextScan(any: String, wmNews: WmNews) {
        try {
            val  map=greenTextScan.greeTextScan("any")
            if (map["suggestion"] !="pass"){
                if (map["suggestion"] =="block"){
                    updateWmNews(wmNews,2,"文本中有敏感词")
                    return
                }
                if (map["suggestion"] == "review"){
                    updateWmNews(wmNews,3,"aliyun也不知道你写的啥")
                    return
                }
            }

        }catch (e:Exception ){
            println(e.message)
            return
        }

    }


    /**
     * 存储纯文本内容
     */
    private fun handleTextAndImages(wmNews: WmNews): mm {
//        var map = mutableMapOf<String,Any>()
        var imagesList = mutableListOf<String>()
        var text =StringBuilder()
        //将文章内容中的图片加到集合中
        wmNews.content.apply {
            val jsonArray = JSONArray.parseArray(this)
            jsonArray.forEach {

                var objects =JSONObject(it.toString())
                if (objects.get("type")=="text"){
                    text.append(objects.get("value"))
                }
                if (objects.get("type")=="image"){
                    imagesList.add(objects.get("value").toString())
                }

            }
        }
        //将封面图片加到集合中
        if (wmNews.images.isNotBlank() && wmNews.type.toInt()!=0){
            imagesList.addAll(wmNews.images.split(","))
        }
        return mutableMapOf<String,Any>("content" to text,"images" to imagesList)
    }


    /**
     * 保存app文章相关的数据
     */
    private fun saveAppArticle(wmNews: WmNews){
        //保存app文章
        var apArticle: ApArticle = saveArticle(wmNews)
        //保存app文章配置
        saveArticleConfig(apArticle)
        //保存app文章内容
        saveArticleContent(apArticle, wmNews)

        //修改自媒体文章的状态为9
        updateWmNews(wmNews, 9.toShort(), "审核通过")
    }

    /**
     * 修改自媒体的文章状态为9
     */
   /* private fun updateWmNews(wmNews: WmNews, articleShort: Short, refuseReason: String="审核通过") =wemediaFeign.updateWmNews(wmNews.apply {
        status=articleShort
        reason=refuseReason
    })*/
    private fun updateWmNews(wmNews: WmNews, articleShort: Short, refuseReason: String) =wemediaFeign.updateWmNews(wmNews.apply {
        status=articleShort
        reason=refuseReason
    })

    /**
     * 保存文章详情
     */
    private fun saveArticleContent(apArticle: ApArticle, wmNews: WmNews) =articleFeign.saveArticleContent(ApArticleContent().apply {
        content=wmNews.content
        articleId=apArticle.id
    })

    /**
     * 保存文章配置
     */
    private fun saveArticleConfig(apArticle: ApArticle)=articleFeign.saveArticleConfig(ApArticleConfig().apply {
        articleId=apArticle.id
        isForward=true
        isDelete=false
        isDown=true
        isComment=true
    })

    /**
     * 保存app文章
     */
    private fun saveArticle(wmNews: WmNews): ApArticle =articleFeign.saveArticle(ApArticle().apply {
        wmNews.let {
            title=wmNews.title
            layout=wmNews.type
            images=wmNews.images
            createdTime= Date()

            wemediaFeign.findWmUserById(it.userId.toInt()).also {a->
                if (a!=null){
                    articleFeign.selectAuthorByName(a.name).let {b->
                        if (b!= null){
                            authorId=b.id.toLong()
                            authorName=b.name
                        }
                    }
                }
            }

            adChannelMapper.selectById(wmNews.channelId).let {c->
                if (c!=null){
                    channelId=c.id
                    channelName=c.name
                }
            }
        }

    })


}